import request, { defaultCacheAge } from '@/utils/request'
import { defaultFormValueToJson, defaultValueToJson, defaultValueToString } from '@/utils'
import { clone, eachTree } from 'xe-utils'
import { defaultCol, setFormComponents } from '@/utils/custom'
import { i18n } from '@/i18n'
import type { AxiosRequestConfig } from 'axios'
import type {
  DepType,
  SubType,
  IFListType,
  TemplateUIType,
  BusinessUIFormType,
  BusinessUIQueryType,
  BusinessUITableType,
  BusinessUIFile
} from '@/types/custom'

// 缓存的请求
const cacheUrls = [
  '/api-base/Sub/list',
  '/api-base/Dep/list',
  '/api-mis/Item/list_item',
  '/api-mis/AccountMember/supplier_list',
  '/api-base/Business/GetBusinessTree?cat=0'
]

// @ts-ignore 不校验 i18n.global 规则冲突 (Vue: Type instantiation is excessively deep and possibly infinite.)
const { t } = i18n.global

/**
 * 系统基础
 */
export function useBaseApi() {
  return {
    /**
     * 超级管理员切换登录用户
     * @constructor
     * @param params
     */
    adminGetUserToken: async (params?: object) => {
      return request({
        url: '/api-base/Auth/admin_get_user_token',
        method: 'get',
        params: params
      })
    },
    /**
     * 自定义请求
     * @param config
     * @constructor
     */
    CustomRequest: <T = any>(config: AxiosRequestConfig) => {
      if (cacheUrls.includes(config.url || '')) {
        config.cacheAge = defaultCacheAge
      }
      return request<T>(config)
    },

    /**
     * 获取工作日日历
     * @param params
     * @constructor
     */
    GetYearWorkCalendar: (params?: any) => {
      return request({
        url: '/api-base/WorkCalendar/year_work_calendar',
        method: 'get',
        params
      })
    },

    /**
     * 保存工作日日历
     * @param data
     * @constructor
     */
    PostYearWorkCalendar: (data: { year: number; rows: any[] }) => {
      return request({
        url: `/api-base/WorkCalendar/year_work_calendar?year=${data.year}`,
        method: 'post',
        data
      })
    },
    /**
     * 获取业务
     * @param params
     * @constructor
     */
    GetBusinessTree: async (params?: object) => {
      return request<RouteItems>({
        url: '/api-base/Business/GetBusinessTree?cat=0',
        method: 'get',
        params
      }).then((res) => {
        eachTree(res.data, (item) => {
          item.title = t(item.meta.title || '')
          item.actions.forEach((v: RouteActionItem) => {
            defaultValueToJson(v, 'default_value')
          })
        })
        return res
      })
    },
    /**
     * 编辑业务
     * @param data
     * @constructor
     */
    EditBusiness: (data?: any) => {
      return request({
        url: '/api-base/Business/EditBusiness',
        method: 'post',
        data
      })
    },
    /**
     * 删除业务
     * @param id
     * @constructor
     */
    DelBusiness: (id: any) => {
      return request({
        url: `/api-base/Business/DelBusiness/${id}`,
        method: 'delete'
      })
    },
    /**
     * 获取列表可选对象（表格）
     * @constructor
     */
    GetIFList: () => {
      return request<IFListType[]>({
        url: '/api-base/BusinessUI/GetIFList',
        method: 'get',
        cacheAge: defaultCacheAge
      })
    },
    /**
     * 获取列表可选对象（查询栏）
     * @constructor
     */
    GetIFQuery: () => {
      return request<IFListType[]>({
        url: '/api-base/BusinessUI/GetIFQuery',
        method: 'get',
        cacheAge: defaultCacheAge
      })
    },
    /**
     * 获取列表可选对象（表单）
     * @constructor
     */
    GetIFForm: () => {
      return request<IFListType[]>({
        url: '/api-base/BusinessUI/GetIFForm',
        method: 'get',
        cacheAge: defaultCacheAge
      })
    },
    /**
     * 保存业务的UI配置
     * @param data
     * @constructor
     */
    SaveBusinessUI: (data: BusinessUITableType) => {
      // 默认值转换String
      defaultValueToString(data, 'default_value')
      data.columns.forEach((v) => {
        defaultValueToString(v, 'set_json')
      })
      data.children?.forEach((v) => {
        defaultValueToString(v, 'default_value')
      })
      return request({
        url: '/api-base/BusinessUI/SaveBusinessUI',
        method: 'put',
        data
      })
    },
    /**
     * 获取业务的UI配置（表格）
     * @param id
     * @constructor
     */
    GetBusinessUI: async (id: string) => {
      return request<BusinessUITableType>({
        url: `/api-base/BusinessUI/GetBusinessUI/${id}`,
        method: 'get',
        cacheAge: defaultCacheAge
      }).then((res) => {
        defaultValueToJson(res.data, 'default_value')
        res.data.columns.forEach((v) => {
          defaultValueToJson(v, 'set_json')
          if (!v.set_json_parse.props) {
            v.set_json_parse.props = {}
          }
        })
        res.data.children?.forEach((v) => {
          defaultValueToJson(v, 'default_value')
        })
        return res
      })
    },
    /**
     * 获取业务的所有UI配置（表格）
     * @param id
     * @param isFormatValue // 是否提前格式化default_value里面的__me__等等关键字
     * @constructor
     */
    get_business_ui: async (id?: string, isFormatValue?: boolean) => {
      if (!id) return Promise.reject('id is undefined')
      return request<TemplateUIType>({
        url: `/api-base/BusinessUI/get_business_ui/${id}`,
        method: 'get',
        cacheAge: defaultCacheAge
      }).then((res) => {
        console.log('业务 id =>', res.data.ui_table?.id || res.data.ui_form?.id)
        res.data.actions.forEach((v) => {
          // 按钮默认值转JSON
          defaultValueToJson(v, 'default_value', isFormatValue)
        })
        // 表单默认值转JSON
        defaultFormValueToJson(res.data.ui_form, isFormatValue)
        // 表格默认值转JSON
        defaultFormValueToJson(res.data.ui_table, isFormatValue)
        // 查询栏默认值转JSON
        defaultFormValueToJson(res.data.ui_query, isFormatValue)
        return res
      })
    },
    /**
     * 获取业务的UI配置（查询栏）
     * @param id
     * @param isFormatValue // 是否提前格式化default_value里面的__me__等等关键字
     * @constructor
     */
    GetBusinessUIQuery: async (id: string, isFormatValue?: boolean) => {
      return request<BusinessUIQueryType>({
        url: `/api-base/BusinessUI/GetBusinessUIQuery/${id}`,
        method: 'get',
        cacheAge: defaultCacheAge
      }).then((res) => {
        // 查询栏默认值转JSON
        defaultValueToJson(res.data, 'default_value', isFormatValue)
        // 表单需要的值
        setFormComponents(res.data.items)
        // 数组
        res.data.items.forEach((v) => {
          // 查询栏默认值转JSON
          defaultValueToJson(v, 'set_json', isFormatValue)
          defaultValueToJson(v, 'default_value', isFormatValue)
          if (!v.set_json_parse.col) {
            v.set_json_parse.col = clone(defaultCol, true)
          }
          if (!v.set_json_parse.props) {
            v.set_json_parse.props = {}
          }
        })
        return res
      })
    },
    /**
     * 保存业务的UI配置（查询栏）
     * @param data
     * @constructor
     */
    SaveBusinessUIQuery: (data: BusinessUIQueryType) => {
      // 默认值转换String
      defaultValueToString(data, 'default_value')
      data.items.forEach((v) => {
        defaultValueToString(v, 'set_json')
        defaultValueToString(v, 'default_value')
      })
      return request({
        url: '/api-base/BusinessUI/SaveBusinessUIQuery',
        method: 'put',
        data
      })
    },
    /**
     * 获取业务的UI配置（表单）
     * @param id
     * @param isFormatValue // 是否提前格式化default_value里面的__me__等等关键字
     * @constructor
     */
    GetBusinessUIForm: async (id: string, isFormatValue?: boolean) => {
      return request<BusinessUIFormType>({
        url: `/api-base/BusinessUI/GetBusinessUIForm/${id}`,
        method: 'get',
        cacheAge: defaultCacheAge
      }).then((res) => {
        // 查询栏默认值转JSON
        defaultValueToJson(res.data, 'default_value', isFormatValue)
        // 表单需要的值
        setFormComponents(res.data.items)
        // 表单默认值
        res.data.items.forEach((v) => {
          // 查询栏默认值转JSON
          defaultValueToJson(v, 'set_json', isFormatValue)
          defaultValueToJson(v, 'default_value', isFormatValue)
          if (!v.set_json_parse.col) {
            v.set_json_parse.col = clone(defaultCol, true)
          }
          if (!v.set_json_parse.props) {
            v.set_json_parse.props = {}
          }
        })
        return res
      })
    },
    /**
     * 保存业务的UI配置（表单）
     * @param data
     * @constructor
     */
    SaveBusinessUIForm: (data: BusinessUIFormType) => {
      // 默认值转换String
      defaultValueToString(data, 'default_value')
      data.items.forEach((v) => {
        defaultValueToString(v, 'set_json')
        defaultValueToString(v, 'default_value')
      })
      return request({
        url: '/api-base/BusinessUI/SaveBusinessUIForm',
        method: 'put',
        data
      })
    },
    /**
     * 获取类型的数据字典
     * @param params
     * @constructor
     */
    GetTypeDictionary: async (params?: object) => {
      return request<any[]>({
        url: '/api-base/BusinessUI/GetTypeDictionary',
        method: 'get',
        params,
        cacheAge: defaultCacheAge
      })
    },
    /**
     * 保存类型的数据字典
     * @param params
     * @param data
     * @constructor
     */
    SaveTypeDictionary: async (params?: object, data?: object) => {
      return request({
        url: '/api-base/BusinessUI/SaveTypeDictionary',
        method: 'put',
        params,
        data
      })
    },
    /**
     * 获取部门
     * @param params
     * @constructor
     */
    GetDepList: async (params?: object) => {
      return request<DepType[]>({
        url: '/api-base/Dep/list',
        method: 'get',
        params,
        cacheAge: defaultCacheAge
      })
    },
    /**
     * 获取公司
     * @param params
     * @constructor
     */
    GetSubList: async (params?: object) => {
      console.log('GetSubList')
      return request<SubType[]>({
        url: '/api-base/Sub/list',
        method: 'get',
        params,
        cacheAge: defaultCacheAge
      })
    },
    /**
     * 获取用户
     * @param data
     * @constructor
     */
    GeUserSearch: async (data?: object) => {
      return request<SubType[]>({
        url: '/api-base/User/search',
        method: 'post',
        data
      })
    },
    /**
     * 获取可选部门和用户
     * @param data
     */
    search_all_users: async (data?: object) => {
      return request<{ deps: any[]; users: any[] }>({
        url: '/api-base/User/search_all_users',
        method: 'post',
        data,
        cacheAge: defaultCacheAge
      })
    }
  }
}

// /**
//  * 系统基础（岗位）
//  */
// export function useBasePositionApi() {
//     return {
//         /**
//          * 岗位查询
//          * @param data
//          * @constructor
//          */
//         GetPositionQuery: async (data?: object) => {
//             return request<{
//                 position_name: string;
//                 id: string;
//                 dep_name: string
//             }[]>({
//                 url: '/api-base/Position/query',
//                 method: 'post',
//                 data
//             })
//         }
//     }
// }

/**
 * 系统基础（文件）
 */
export function useBaseFileApi() {
  return {
    /**
     * 下载文件
     * @param id
     * @constructor
     */
    GetBaseFileDown: async (id: string) => {
      return request({
        url: `/api-base/File/down/${id}`,
        responseType: 'blob',
        method: 'get'
      })
    },
    /**
     * 获取文件详情
     * @param id
     * @constructor
     */
    GetBaseFile: async (id: string) => {
      return request<BusinessUIFile>({
        url: `/api-base/File/file_info/${id}`,
        method: 'get'
      })
    },
    /**
     * 上传图片
     * @constructor
     * @param files
     */
    UploadBaseImage: async (files: any) => {
      return request({
        url: '/api-base/File/upload_img',
        method: 'post',
        data: files,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    },
    /**
     * 上传文件
     * @constructor
     * @param files
     */
    UploadBaseFile: async (files: any) => {
      return request({
        url: '/api-base/File/upload_file',
        method: 'post',
        data: files,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    }
  }
}
